package com.aliware.tianchi;

import com.aliware.tianchi.utils.RandomUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;

import com.aliware.tianchi.policy.BaseConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static com.aliware.tianchi.Constants.nacosAddress;

/**
 * @author guohaoice@gmail.com
 */
public class MyProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyProvider.class);

    private static ApplicationConfig application = new ApplicationConfig();
    private static RegistryConfig registry = new RegistryConfig();
    private static ProtocolConfig protocol = new ProtocolConfig();

    public static void main(String[] args) throws InterruptedException {

        BaseConfig config = BaseConfig.loadConf();
        // 当前应用配置
        application.setName("service-provider");
        application.setQosEnable(false);

        // 连接注册中心配置

        registry.setAddress(nacosAddress());


        // 服务提供者协议配置
        protocol.setName("dubbo");
        Integer port = RandomUtils.genInt(4,"3");
        protocol.setPort(port);
        protocol.setThreads(config.getMaxThreadCount());
        protocol.setHost("0.0.0.0");
        application.setMetadataServicePort(port);

        GameChannelHandler.configs = config.getConfigs();
        // 注意：ServiceConfig为重对象，内部封装了与注册中心的连接，以及开启服务端口
        exportHashService(config.getConfigs());

        Thread.currentThread().join();
    }

    private static void exportHashService(ThrashConfig configs) {
        // 服务提供者暴露服务配置
        ServiceConfig<HashInterface> service =
                new ServiceConfig<>();
        Map<String, String> attributes = new HashMap<>();
        attributes.put("heartbeat", "0");
        attributes.put("dispatcher", "game");
        service.setParameters(attributes);
        service.setApplication(application);
        service.setRegistry(registry);
        service.setProtocol(protocol);
        service.setTimeout(5000);
        service.setInterface(HashInterface.class);
        service.setRef(new HashServiceImpl(System.getProperty("salt"), configs));
        // 暴露及注册服务
        service.export();
    }

}
